<template>
  <div>
    <!-- 页面头部 -->
    <Header title="订单管理"></Header>

    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <!-- 可以添加其他操作按钮 -->
    </div>

    <!-- 筛选区域 -->
    <div class="filter-bar">
      <el-form inline>
        <el-form-item label="下单日期">
          <el-date-picker
            v-model="filterDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select style="width: 150px;" v-model="filterStatus" placeholder="请选择订单状态">
            <el-option label="已下单" value="1" />
            <el-option label="已发货" value="2" />
            <el-option label="已签收" value="3" />
            <el-option label="已完成" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 搜索栏区域 -->
    <div class="search-bar">
      <el-input 
        style="width: 500px;" 
        v-model="searchKeyword" 
        placeholder="根据订单编号或买家ID搜索" 
        clearable 
        @input="searchOrders" 
        :prefix-icon="Search" 
      />
    </div>

    <!-- 订单列表表格 -->
    <el-table
      :data="paginatedOrders"
      border
      stripe
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column prop="orderId" label="订单ID" width="80px" align="center" />
      <el-table-column prop="goodsName" label="商品名称" min-width="120" />
      <el-table-column label="商品图片" width="120" align="center">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            fit="contain"
            class="goods-image"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="订单总价" width="120" align="right">
        <template #default="scope">
          ¥{{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="180" />
      <el-table-column prop="status" label="订单状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{
              scope.row.status === 1
                ? '已下单'
                : scope.row.status === 2
                ? '已发货'
                : scope.row.status === 3
                ? '已签收'
                : scope.row.status === 4
                ? '已完成'
                : '未知状态'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sendTime" label="发货时间" width="180" />
      <el-table-column prop="getTime" label="签收时间" width="180" />
      <el-table-column prop="endTime" label="完成时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="confirmDeleteOrder(scope.row.orderId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalOrders"
      />
    </div>

    <!-- 编辑订单弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单" width="600px">
      <el-form :model="editOrder" label-width="100px" ref="editOrderForm">
        <el-form-item label="订单总价">
          <el-input-number v-model="editOrder.amount" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-input v-model="editOrder.payMethod" />
        </el-form-item>
        <el-form-item label="收货人姓名">
          <el-input v-model="editOrder.name" />
        </el-form-item>
        <el-form-item label="收货人手机号">
          <el-input v-model="editOrder.phone" />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="editOrder.address" />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="editOrder.addressInfo" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="editOrder.status" placeholder="请选择订单状态">
            <el-option label="已下单" :value="1" />
            <el-option label="已发货" :value="2" />
            <el-option label="已签收" :value="3" />
            <el-option label="已完成" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveEditOrder">保存</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Header from '@/views/ui/header.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getOrdersListApi, updateOrdersInfoApi, deleteOrdersByIdApi } from '@/apis/OrdersManagerApi';
import { Search } from '@element-plus/icons-vue'

const ordersList = ref([]);
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalOrders = ref(0);
const paginatedOrders = ref([]);
const editDialogVisible = ref(false);
const editOrder = ref({});

// 筛选条件
const filterDateRange = ref(null);
const filterStatus = ref(null);

const fetchOrdersList = async () => {
  try {
    const res = await getOrdersListApi();
    ordersList.value = res.data;
    totalOrders.value = ordersList.value.length;
    applyFiltersAndPagination();
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  }
};

const applyFiltersAndPagination = () => {
  let filteredOrders = ordersList.value.filter(order => {
    // 筛选下单日期
    if (filterDateRange.value) {
      const [startDate, endDate] = filterDateRange.value;
      const orderDate = new Date(order.createTime).toISOString().split('T')[0];
      if (orderDate < startDate || orderDate > endDate) return false;
    }

    // 筛选订单状态
    if (filterStatus.value && order.status.toString() !== filterStatus.value) return false;

    // 搜索关键词
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      if (!order.orderId.toString().includes(keyword) && 
          !order.buyId.toString().includes(keyword)) {
        return false;
      }
    }

    return true;
  });

  totalOrders.value = filteredOrders.length;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedOrders.value = filteredOrders.slice(start, end);
};

const handleSizeChange = size => {
  pageSize.value = size;
  applyFiltersAndPagination();
};

const handleCurrentChange = page => {
  currentPage.value = page;
  applyFiltersAndPagination();
};

const applyFilters = () => {
  currentPage.value = 1;
  applyFiltersAndPagination();
};

const resetFilters = () => {
  filterDateRange.value = null;
  filterStatus.value = null;
  searchKeyword.value = '';
  applyFiltersAndPagination();
};

const searchOrders = () => {
  currentPage.value = 1;
  applyFiltersAndPagination();
};

const openEditDialog = order => {
  editOrder.value = { ...order };
  editDialogVisible.value = true;
};

const saveEditOrder = async () => {
  try {
    await updateOrdersInfoApi(editOrder.value);
    ElMessage.success('订单更新成功');
    editDialogVisible.value = false;
    fetchOrdersList();
  } catch (error) {
    console.error('更新订单失败:', error);
    ElMessage.error('更新订单失败');
  }
};

const confirmDeleteOrder = orderId => {
  ElMessageBox.confirm('确定要删除该订单吗？此操作不可撤销', '确认删除', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOrdersByIdApi(orderId);
      ElMessage.success('订单删除成功');
      fetchOrdersList();
    } catch (error) {
      console.error('删除订单失败:', error);
      ElMessage.error('删除订单失败');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const getStatusTagType = status => {
  switch (status) {
    case 1: return 'warning';  // 已下单 - 黄色
    case 2: return 'primary';  // 已发货 - 蓝色
    case 3: return 'success';  // 已签收 - 绿色
    case 4: return 'info';     // 已完成 - 青色
    default: return 'danger';  // 未知状态 - 红色
  }
};

onMounted(() => {
  fetchOrdersList();
});
</script>

<style lang="scss" scoped>
.operation-bar {
  margin-bottom: 20px;
}

.filter-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: contain;
  cursor: pointer;
}

.el-table {
  margin-top: 20px;
  
  :deep(.cell) {
    white-space: nowrap;
  }
}

.el-dialog {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
}
</style>